using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.RegularExpressions;
using Volo.Abp;
using Volo.Abp.Validation;

namespace CKY.AgentPlatform.Validation
{
    /// <summary>
    /// 数据验证帮助类
    /// </summary>
    public static class ValidationHelper
    {
        /// <summary>
        /// 验证URL格式
        /// </summary>
        public static bool IsValidUrl(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
                return false;

            return Uri.TryCreate(url, UriKind.Absolute, out var uriResult) 
                && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
        }

        /// <summary>
        /// 验证邮箱格式
        /// </summary>
        public static bool IsValidEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
                return false;

            var emailRegex = new Regex(@"^[^@\s]+@[^@\s]+\.[^@\s]+$");
            return emailRegex.IsMatch(email);
        }

        /// <summary>
        /// 验证智能体名称
        /// </summary>
        public static void ValidateAgentName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
                throw new UserFriendlyException("智能体名称不能为空");

            if (name.Length < 2 || name.Length > 50)
                throw new UserFriendlyException("智能体名称长度必须在2-50个字符之间");

            if (!Regex.IsMatch(name, @"^[\u4e00-\u9fa5a-zA-Z0-9\s\-_]+$"))
                throw new UserFriendlyException("智能体名称只能包含中文、英文、数字、空格、连字符和下划线");
        }

        /// <summary>
        /// 验证模型配置名称
        /// </summary>
        public static void ValidateModelConfigName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
                throw new UserFriendlyException("模型配置名称不能为空");

            if (name.Length < 2 || name.Length > 100)
                throw new UserFriendlyException("模型配置名称长度必须在2-100个字符之间");

            if (!Regex.IsMatch(name, @"^[\u4e00-\u9fa5a-zA-Z0-9\s\-_\.]+$"))
                throw new UserFriendlyException("模型配置名称只能包含中文、英文、数字、空格、连字符、下划线和点号");
        }

        /// <summary>
        /// 验证MCP服务器URL
        /// </summary>
        public static void ValidateMcpServerUrl(string serverUrl)
        {
            if (string.IsNullOrWhiteSpace(serverUrl))
                throw new UserFriendlyException("MCP服务器URL不能为空");

            if (!IsValidUrl(serverUrl))
                throw new UserFriendlyException("MCP服务器URL格式不正确");

            if (!serverUrl.StartsWith("http://") && !serverUrl.StartsWith("https://"))
                throw new UserFriendlyException("MCP服务器URL必须以http://或https://开头");
        }

        /// <summary>
        /// 验证超时时间
        /// </summary>
        public static void ValidateTimeout(int timeoutMs, string fieldName = "超时时间")
        {
            if (timeoutMs < 1000)
                throw new UserFriendlyException($"{fieldName}不能小于1000毫秒");

            if (timeoutMs > 300000)
                throw new UserFriendlyException($"{fieldName}不能大于300000毫秒（5分钟）");
        }

        /// <summary>
        /// 验证提示词模板内容
        /// </summary>
        public static void ValidatePromptTemplateContent(string content)
        {
            if (string.IsNullOrWhiteSpace(content))
                throw new UserFriendlyException("提示词模板内容不能为空");

            if (content.Length < 10)
                throw new UserFriendlyException("提示词模板内容不能少于10个字符");

            if (content.Length > 10000)
                throw new UserFriendlyException("提示词模板内容不能超过10000个字符");
        }

        /// <summary>
        /// 验证工具配置JSON
        /// </summary>
        public static void ValidateToolConfiguration(string configuration)
        {
            if (string.IsNullOrWhiteSpace(configuration))
                throw new UserFriendlyException("工具配置不能为空");

            try
            {
                // 尝试解析JSON
                var json = System.Text.Json.JsonDocument.Parse(configuration);
                
                // 验证是否包含必要的字段
                if (!json.RootElement.TryGetProperty("name", out _))
                    throw new UserFriendlyException("工具配置必须包含name字段");

                if (!json.RootElement.TryGetProperty("description", out _))
                    throw new UserFriendlyException("工具配置必须包含description字段");
            }
            catch (System.Text.Json.JsonException)
            {
                throw new UserFriendlyException("工具配置必须是有效的JSON格式");
            }
        }

        /// <summary>
        /// 验证分页参数
        /// </summary>
        public static void ValidatePagingParams(int skipCount, int maxResultCount)
        {
            if (skipCount < 0)
                throw new UserFriendlyException("跳过数量不能小于0");

            if (maxResultCount < 1)
                throw new UserFriendlyException("最大结果数量不能小于1");

            if (maxResultCount > 1000)
                throw new UserFriendlyException("最大结果数量不能超过1000");
        }

        /// <summary>
        /// 验证ID格式
        /// </summary>
        public static void ValidateId(string id, string entityName = "实体")
        {
            if (string.IsNullOrWhiteSpace(id))
                throw new UserFriendlyException($"{entityName}ID不能为空");

            if (id.Length != 36 && id.Length != 32) // GUID或MD5格式
                throw new UserFriendlyException($"{entityName}ID格式不正确");
        }

        /// <summary>
        /// 验证标签格式
        /// </summary>
        public static void ValidateTags(string tags)
        {
            if (string.IsNullOrWhiteSpace(tags))
                return;

            var tagList = tags.Split(',', StringSplitOptions.RemoveEmptyEntries);
            
            if (tagList.Length > 10)
                throw new UserFriendlyException("标签数量不能超过10个");

            foreach (var tag in tagList)
            {
                var trimmedTag = tag.Trim();
                if (trimmedTag.Length < 1 || trimmedTag.Length > 20)
                    throw new UserFriendlyException("每个标签长度必须在1-20个字符之间");

                if (!Regex.IsMatch(trimmedTag, @"^[a-zA-Z0-9\u4e00-\u9fa5\-_]+$"))
                    throw new UserFriendlyException("标签只能包含中文、英文、数字、连字符和下划线");
            }
        }

        /// <summary>
        /// 验证数值范围
        /// </summary>
        public static void ValidateRange<T>(T value, T min, T max, string fieldName) where T : IComparable<T>
        {
            if (value.CompareTo(min) < 0 || value.CompareTo(max) > 0)
                throw new UserFriendlyException($"{fieldName}必须在{min}到{max}之间");
        }

        /// <summary>
        /// 验证必需字段
        /// </summary>
        public static void ValidateRequired(object value, string fieldName)
        {
            if (value == null)
                throw new UserFriendlyException($"{fieldName}不能为空");

            if (value is string str && string.IsNullOrWhiteSpace(str))
                throw new UserFriendlyException($"{fieldName}不能为空");
        }

        /// <summary>
        /// 验证字符串长度
        /// </summary>
        public static void ValidateStringLength(string value, int minLength, int maxLength, string fieldName)
        {
            if (string.IsNullOrEmpty(value))
                return;

            if (value.Length < minLength || value.Length > maxLength)
                throw new UserFriendlyException($"{fieldName}长度必须在{minLength}到{maxLength}个字符之间");
        }
    }

    /// <summary>
    /// 自定义验证属性
    /// </summary>
    public class AgentNameAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value == null)
                return false;

            var name = value as string;
            if (string.IsNullOrWhiteSpace(name))
                return false;

            return name.Length >= 2 && name.Length <= 50 && 
                   Regex.IsMatch(name, @"^[\u4e00-\u9fa5a-zA-Z0-9\s\-_]+$");
        }

        public override string FormatErrorMessage(string name)
        {
            return $"{name}只能包含中文、英文、数字、空格、连字符和下划线，长度必须在2-50个字符之间";
        }
    }

    /// <summary>
    /// URL验证属性
    /// </summary>
    public class ValidUrlAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value == null)
                return false;

            var url = value as string;
            return ValidationHelper.IsValidUrl(url);
        }

        public override string FormatErrorMessage(string name)
        {
            return $"{name}必须是有效的URL格式";
        }
    }

    /// <summary>
    /// 标签验证属性
    /// </summary>
    public class ValidTagsAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value == null)
                return true;

            var tags = value as string;
            if (string.IsNullOrWhiteSpace(tags))
                return true;

            try
            {
                ValidationHelper.ValidateTags(tags);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public override string FormatErrorMessage(string name)
        {
            return $"{name}格式不正确，最多10个标签，每个标签1-20个字符";
        }
    }
}